package ws.very.android.util.async.askbox;

import java.util.LinkedList;

import ws.very.util.lang.function.Fn;
import ws.very.util.lang.Colls;



public class EventsBox<T> {
	private T value;
	private LinkedList<Fn<T, Void>> onCompleteCall;

	public synchronized void complete(T v) {
		if (value != null)
			return;
		value = v;
		tryComplete();
	}

	public synchronized EventsBox<T> onComplete(Fn<T, Void> fn) {
		if (fn == null)
			return this;
		addListen(fn);
		tryComplete();
		return this;
	}

	protected void addListen(Fn<T, Void> fn) {
		if (onCompleteCall == null)
			onCompleteCall = new LinkedList<Fn<T, Void>>();
		onCompleteCall.add(fn);
	}

	protected void clearCall() {
		onCompleteCall = null;
	}

	protected void tryComplete() {
		if (value != null && !Colls.isEmpty(onCompleteCall)) {
			for (Fn<T, Void> fn : onCompleteCall) {
				fn.apply(value);
			}
			clearCall();
		}
	}

}
